<template>
  <div class="badInput zy-content ">
    <!-- 搜索 -->
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
        <p class="label">{{$t('设备')}}</p>
        <div class="ipt">
          <Select v-model="searchParams.deviceId" filterable clearable :placeholder="`${$t('common.inputInfo')}`" :remote-method="handleRemote">
            <Option v-for="item in deviceMIdList" :value="item.id" :label="item.desc" :key="item.id" />
          </Select>
        </div>
        </Col>
        <Col span="4">
        <p class="label">{{$t('班次')}}</p>
        <div class="ipt">
          <Select v-model="searchParams.classId" clearable>
            <Option v-for="(item, index) of productionShiftList" :value="item.value" :label="item.name" :key="index"></Option>
          </Select>
        </div>
        </Col>
        <Col span="4">
        <p class="label">{{$t('日期')}}</p>
        <div class="ipt">
          <DatePicker type="date" format="yyyy-MM-dd" v-model="searchParams.scheduleDate" :placeholder="`${$t('common.selectInfo')}`" />
        </div>
        </Col>
        <Col span="4">
        <p class="label hide-label">--</p>
        <div class="ipt">
          <Button class="search-btn" type="primary" @click="changeNum()" v-has="'badInputSearch'">{{$t('common.Query')}}</Button>
          <Button class="reset-btn" @click="resetSearch()" v-has="'badInputSearch'">{{ $t('common.reset') }}</Button>
        </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="createfaultCodeShowH" v-has="'badInputAddEdit'">{{$t('common.New')}}</Button>
        <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}</Button>
      </div>
      <div class="tableContent">
        <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList" ellipsis ref="selection" stripe
               :data="dataArr">
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="createfaultCodeShowH(row)" v-has="'badInputAddEdit'"><i
                 class="iconfont zy-common-bianji"></i>{{$t('common.Edit')}}</span>
          </template>
        </Table>
      </div>
      <!-- 分页 -->
      <div class="pageWrap mt16">
        <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum" @on-change="changePageNum"
              @on-page-size-change="changePageSize" show-sizer show-total />
      </div>
    </div>
    <!-- 新增编辑 -->
    <Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout">
      <Form ref="form" :model="formItem" label-position="top" :rules="ruleValidate">
        <FormItem :label="$t('设备')" prop="deviceId">
          <Select v-model="formItem.deviceId" filterable clearable :placeholder="`${$t('common.inputInfo')}`" @on-query-change="handleRemote">
            <Option v-for="item in deviceMIdList" :value="item.id" :label="item.desc" :key="item.id" />
          </Select>
        </FormItem>
        <FormItem :label="$t('班次')" prop="classId">
          <Select v-model="formItem.classId" clearable>
            <Option v-for="(item, index) of productionShiftList" :value="item.value" :label="item.name" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('班次日期')" prop="scheduleDate">
          <DatePicker type="date" format="yyyy-MM-dd" v-model="formItem.scheduleDate" :placeholder="`${$t('common.selectInfo')}`" />
        </FormItem>
        <FormItem :label="$t('数量')" prop="quantity">
          <InputNumber :min="0" :formatter="value => `${parseInt(value)}`" style="width: 100%" v-model="formItem.quantity" clearable
                       :placeholder="`${$t('common.inputInfo')}`"></InputNumber>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="create = false">{{$t('common.Cancle')}}</Button>
        <Button type="primary" :loading="loading" @click="addOk('form')">{{$t('maintenance.Confirmed')}}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { searchApi, addApi } from '@/api/qualityManage/badInput/index.js'
import toggleTableOperation from '@/mixins/toggleTableOperation'
export default {
  name: 'badInput',
  components: {},
  mixins: [toggleTableOperation],
  data() {
    return {
      productionShiftList: [
        {
          value: 0,
          name: '早班（8H）'
        },
        {
          value: 1,
          name: '中班（8H）'
        },
        {
          value: 2,
          name: '白班（12H）'
        },
        {
          value: 3,
          name: '常白班（8H）'
        },
        {
          value: 4,
          name: '夜班（12H）'
        }
      ],
      deviceMIdList: [],
      formItem: {},
      addtitle: '',
      loading: false,
      create: false,
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      columns: [
        {
          title: `${this.$t('设备流水号')}`,
          key: 'deviceCode',
          minWidth: 100,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('班次')}`,
          key: 'className',
          minWidth: 100,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('班次日期')}`,
          key: 'scheduleDate',
          minWidth: 100,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('不良品数')}`,
          key: 'quantity',
          minWidth: 100,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('创建人')}`,
          key: 'createByName',
          minWidth: 100,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('创建时间')}`,
          key: 'createTime',
          minWidth: 100,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: 'action',
          fixed: 'right',
          width: 100,
          align: 'center'
        }
      ],
      dataArr: [],
      ruleValidate: {
        deviceId: [{ required: true, type: 'number', message: this.$t('common.selectInfo'), trigger: 'change' }],
        classId: [{ required: true, type: 'number', message: this.$t('common.selectInfo'), trigger: 'change' }],
        scheduleDate: [{ required: true, type: 'date', message: this.$t('common.selectInfo'), trigger: 'change' }],
        quantity: [{ required: true, type: 'number', message: this.$t('common.inputInfo'), trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getTableColumnsWidth(this.columns)
  },
  mounted() {
    this.searchList()
  },
  methods: {
    debounceSerach(fn, delay) {
      let _this = this
      return function f(...args) {
        if (_this.timeID) {
          clearTimeout(_this.timeID)
        }
        _this.timeID = setTimeout(() => {
          fn(args)
        }, delay)
      }
    },
    handleRemote(query) {
      if (!query) {
        return
      }
      const fn = this.debounceSerach(() => {
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        this.axios({
          method: 'get',
          url: '/dms/dmsDevice/deviceList',
          params: {
            deviceMId: _query
          }
        }).then(res => {
          if (res.code === 200) {
            this.deviceMIdList = res.data.map(item => {
              item.desc = item.deviceMId + '-' + item.deviceName + '-' + item.deviceNo
              return item
            })
          }
        })
      }, 300)
      fn()
    },
    resetSearch() {
      this.searchParams = {}
      this.searchList()
    },
    //分页
    changeNum() {
      this.pageNum = 1
      this.searchList()
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize
      this.searchList()
    },
    changePageNum(val) {
      this.pageNum = val
      this.searchList()
    },
    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }
      for (let key in this.searchParams) {
        if (this.searchParams[key] || this.searchParams[key] === 0) {
          this.$set(params, key, this.searchParams[key])
        }
      }
      if (params.scheduleDate) {
        params.scheduleDate = this.$moment(params.scheduleDate).format('YYYY-MM-DD')
      }
      searchApi(params).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    //增加或编辑
    async createfaultCodeShowH(row) {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      if (row.id) {
        this.addtitle = `${this.$t('common.Edit')}`
        this.formItem = {
          id: row.id,
          deviceId: row.deviceId,
          classId: row.classId,
          quantity: row.quantity,
          scheduleDate: new Date(row.scheduleDate)
        }
        this.deviceMIdList = [{ desc: row.deviceCode + '-' + row.deviceName, id: row.deviceId }]
      } else {
        this.addtitle = `${this.$t('common.New')}`
        this.formItem = {
            quantity:null
        }
      }
      this.create = true
    },
    addOk(name) {
      this.$refs[name].validate(valid => {
        if (!valid) {
          return
        } else {
          this.loading = true
          let params = {}
          for (let key in this.formItem) {
            if (this.formItem[key] || this.formItem[key] === 0) {
              this.$set(params, key, this.formItem[key])
            }
          }
          if (params.scheduleDate) {
            params.scheduleDate = this.$moment(params.scheduleDate).format('YYYY-MM-DD')
          }
          addApi(params).then(res => {
            this.loading = false
            if (res.code === 200) {
              this.changeNum()
              this.$Message.success(res.msg)
              this.create = false
            } else {
              this.$Message.warning({ content: res.msg, duration: 6, closable: true })
            }
          })
        }
      })
    }
  }
}
</script>
